package com.loe.test

import android.content.Context
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.PlaybackException
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.loe.mvp.ext_java.int

/**
 * 音频播放器
 *
 * @author 章路顺
 * @since 2023/3/10-15:25
 */
object MyPlayer
{
    var player: SimpleExoPlayer? = null
        private set

    var speed = 1.2f

    private var onStart: (() -> Unit)? = null
    private var onStop: (() -> Unit)? = null
    private var onItemStart: ((Int) -> Unit)? = null

    fun setOnStart(onStart: () -> Unit)
    {
        this.onStart = onStart
    }

    fun setOnStop(onStop: () -> Unit)
    {
        this.onStop = onStop
    }

    fun setOnItemStart(onItemStart: (Int) -> Unit)
    {
        this.onItemStart = onItemStart
    }

    fun play(context: Context, url: String)
    {
        play(context, listOf(PlayBean(url)))
    }

    fun play(context: Context, list: List<PlayBean>)
    {
        if (isPlaying)
        {
            stop()
        } else
        {
            onStart?.invoke()
            player?.release()
            player = SimpleExoPlayer.Builder(context).build()
            player?.setPlaybackSpeed(speed)
            player?.addListener(object : Player.Listener
            {
                override fun onPlaybackStateChanged(playbackState: Int)
                {
                    if (playbackState == Player.STATE_ENDED)
                    {
                        player?.release()
                        onStop?.invoke()
                    }
                }

                override fun onPlayerError(error: PlaybackException)
                {
                    player?.release()
                    onStop?.invoke()
                }

                override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int)
                {
                    if (mediaItem != null)
                    {
                        onItemStart?.invoke(mediaItem.mediaId.int)
                    }
                }
            })
            list.forEachIndexed()
            { index, playBean ->
                if (playBean.index < 0) playBean.index = index
                player?.addMediaItem(MediaItem.Builder().setUri(playBean.url).setMediaId(playBean.index.toString()).build())
            }
            player?.prepare()
            player?.play()
        }
    }

    fun stop()
    {
        player?.stop()
        player?.release()
        onStop?.invoke()
    }

    val isPlaying get() = player?.isPlaying == true
}

class PlayBean(var url: String, var index: Int = -1)